# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < FacebookController
  helper :all # include all helpers, all the time
  #include Facebooker2::Rails::Controller
  #include ExFacebook::Rails::Controller
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password, :password_confirmation
  protect_from_forgery 
  layout 'default'
  #Facebooker2.app_id = WEBAPP_CONFIG["facebook_client_id"]
  #Facebooker2.api_key = WEBAPP_CONFIG["facebook_key"]
  #Facebooker2.secret = WEBAPP_CONFIG["facebook_secret"]
  before_filter :ensure_is_authenticated_in_fb
  
  
  protected
  #Convenience method to add an error to the flash
  def flash_error(message_key,*strs)
    flash[:error] = sprintf(I18n.t(message_key),*strs)
  end
  
  #Convenience method to add and note to flash
  def flash_notice(message_key, *strs)
    flash[:notice] = sprintf(I18n.t(message_key),*strs)
  end
  
  private
  
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end
  
  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end
  
  def require_user
    unless current_user
      store_location
      flash[:notice] = "You must be logged in to access this page"
      redirect_to new_user_session_url
      return false
    end
  end
  
  def require_no_user
    if current_user
      store_location
      flash[:notice] = "You must be logged out to access this page"
      redirect_to account_url
      return false
    end
  end
  
  def store_location
    session[:return_to] = request.request_uri
  end
  
  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end
end
